#include <SPI.h>

void SPIMasterSetup()
{
  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  pinMode(MISO, INPUT);
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

	SPI.begin (); // put SPI hardware into Master mode and turn SPI on
	SPI.setClockDivider(SPI_CLOCK_DIV8); // Slow down the master a bit
}


void SPI_GetLineSensorData() { _SPI_GetData(SPICMD_REQUEST_LINEDATA, &lineSensorData); }
void SPI_GetWallSensorData() { _SPI_GetData(SPICMD_REQUEST_WALLDATA, &wallSensorData); }
void SPI_GetButtonData() { _SPI_GetData(SPICMD_REQUEST_BUTTONDATA, &buttonData); }
void SPI_GetRFString() { _SPI_GetData(SPICMD_REQUEST_RF_STRING, &RFRFInString); }

void SPI_SetLED() { _SPI_SetData(SPICMD_SEND_LEDDATA, &LEDData, sizeof(LEDData)-1; }
void SPI_SetRobotMode() { _SPI_SetData(SPICMD_SEND_LEDDATA, &mode, sizeof(mode)-1; }
void SPI_SetOLEDString() { _SPI_SetData(SPICMD_SEND_OLED_STRING, &OLEDString, sizeof(*OLEDString)-1; }
void SPI_SetRFString() { _SPI_SetData(SPICMD_SEND_RF_STRING, &RFOutString, sizeof(*RFOutString)-1; }


void _SPI_GetData(uint8_t spiCmd,char *data)
{
  digitalWrite(SS, LOW);
  spi_send(spiCmd);
  uint8_t dataSize = spi_send(spiCmd);
    for (int n = 0 ;n < dataSize; n++)
    {
      *(data+n) = spi_send(spiCmd);
    }
  digitalWrite(SS, HIGH);
  
  *(data+dataSize+1) = true;
}

void _SPI_SetData(uint8_t spiCmd,char *data, uint8_t dataSize)
{
  digitalWrite(SS, LOW);
  spi_send(spiCmd);
  uint8_t dataSize = spi_send(dataSize);
  for (int n = 0 ;n < dataSize; n++)
  {
    spi_send(*(data+n));
  }
  digitalWrite(SS, HIGH);
  
  *(data+dataSize+1) = false;
}

uint8_t spi_send(uint8_t b) {
  //digitalWrite(SS, LOW);
  uint8_t reply;
  SPDR = b;
  do {} while (!(SPSR & (1 << SPIF)));
  reply = SPDR;
  //digitalWrite(SS, HIGH);
  return reply;
}
